import {Component, OnDestroy, OnInit} from '@angular/core';
import {Observable} from 'rxjs/Observable';
import {PortalsService} from '../../portals.service';
import {Menu} from '../../../models/menu';
import {AppConstants, PermissionType} from '../../../constants/constants';
import {MsgResult} from '../../../models/msg-result';
import {PortalUtilService} from '../../portal-util.service';
import {ResponseUtil} from '../../../util/response-util';
import {TreeUtil} from '../../../util/tree-util';
import {MenuSubject} from '../../../subject/menu-subject';
import {Subscription} from 'rxjs/Subscription';

declare var $;

@Component({
  selector: 'app-datav-sidebar',
  templateUrl: './datav-sidebar.component.html',
  styleUrls: ['./datav-sidebar.component.css']
})

export class DatavSidebarComponent implements OnInit, OnDestroy {

  menus: Menu[];
  cacheMenus: Menu[];
  private subscription: Subscription;
  screenSizes = {
    xs: 480,
    sm: 768,
    md: 992,
    lg: 1200
  };

  constructor(
    private portalsService: PortalsService,
    private portalUtilService: PortalUtilService,
    private responseUtil: ResponseUtil,
    private menuSubject: MenuSubject,
    private treeUtil: TreeUtil
  ) { }

  ngOnInit() {
    this.initAdminLte();
    this.getMenus();
    this.hideSideBar();
    this.reSize();
  }
  ngOnDestroy() {
    this.unSubscribeSysId();
  }
  initAdminLte() {
    if (!$.AdminLTE) {
      this.portalUtilService.initAdminLte();
    }
  }

  /**
   * 侧边栏显示隐藏
   */
  setSidebar() {
    if (!this.menus || this.menus.length <= 0) {
      this.hideSideBar();
    } else {
      this.showSideBar();
    }
    this.contentHeight();
    this.resetTableWidth();
  }

  hideSideBar() {
    // this.collapseSidebar();
    $('.main-sidebar').css('width', 0);
    $('.content-wrapper').css('marginLeft', 0);
    $('.main-footer').css('marginLeft', 0);
  }

  showSideBar() {
    // this.expandedSidebar();
    $('.main-sidebar').css('width', '230px');
    $('.content-wrapper').css('marginLeft', '230px');
    $('.main-footer').css('marginLeft', '230px');
  }
  reSize() {
    $(window).resize(() => {
      if ($(window).width() > (this.screenSizes.sm - 1) && $('.main-sidebar').css('width') === '0px') {
        this.showSideBar();
        console.log('show');
      } else if ($(window).width() <= (this.screenSizes.sm - 1) && $('.main-sidebar').css('width') === '230px') {
        console.log('hide');
        this.hideSideBar();
      }
    });
  }
  contentHeight() {
    const neg = $('.main-header').outerHeight() + $('.main-footer').outerHeight();
    const window_height = $(window).height();
    const sidebar_height = $('.sidebar').height();
    if ($('body').hasClass('fixed')) {
      $('.content-wrapper, .right-side').css('min-height', window_height - $('.main-footer').outerHeight());
    } else {
      let postSetWidth;
      if (window_height >= sidebar_height) {
        $('.content-wrapper, .right-side').css('min-height', window_height - neg);
        postSetWidth = window_height - neg;
      } else {
        $('.content-wrapper, .right-side').css('min-height', sidebar_height);
        postSetWidth = sidebar_height;
      }
      const controlSidebar = $('.control-sidebar');
      if (typeof controlSidebar !== 'undefined') {
        if (controlSidebar.height() > postSetWidth) {
          $('.content-wrapper, .right-side').css('min-height', controlSidebar.height());
        }
      }
    }
  }
  resetTableWidth = () => {
    setTimeout(() => {
      const tableWidth = $('.one-table-area .fixed-table-body>.table').outerWidth();
      $('.one-table-area .fixed-table-header>.table').css('width', tableWidth + 'px');
    }, 320)
  };
  /**
   * 订阅菜单系统ID
   */
  subscribeSysId() {
    this.subscription = this.menuSubject.subscribeData().subscribe(
      (data) => {
        console.log('系统ID订阅');
        if (data) {
          const filterMenu = this.cacheMenus.filter((val) => {
            return val.id === data;
          });
          this.menus = filterMenu[0].children || [];
          this.setSidebar();
        }
      }
    );
  }
  private unSubscribeSysId() {
    if (this.subscription) {
      console.log('取消系统ID订阅');
      this.subscription.unsubscribe();
    }
  }
  private getMenus() {
    this.getMenusByConfig().subscribe(
      result => this.responseUtil.success(result, this.process),
      error => this.responseUtil.error(error)
    );
  }

  private getMenusByConfig(): Observable<any> {
    if (AppConstants.sysId) {
      return this.portalsService.getChildMenus(AppConstants.sysId);
    }else {
      return this.portalsService.getPermissions(PermissionType.menus);
    }
  }


  private process = (result: MsgResult) => {
    const rootId = AppConstants.sysId ? AppConstants.sysId : null;
    const rootNode = {id: rootId};
    this.cacheMenus = result.data;
    const ownedMneus: any = this.treeUtil.filterNodes(rootNode, result.data);
    if (ownedMneus.length === 0) {
      this.menus = [];
    }else {
      this.menus = ownedMneus[0].children;
    }
    this.setSidebar();
    if (!rootId) {
      this.subscribeSysId();
    }
  }
}
